<?php

namespace backend\models;

use Yii;
use common\models\UserInfo;
use yii\helpers\ArrayHelper;
use yii\db\ActiveRecord;
use backend\models\SysItem;
use backend\models\ItemPreview;
use backend\models\SysItemPrices;

class CrowdItem extends \yii\db\ActiveRecord
{
	public $item;
	public $fid;
	public $mid;
	public $sid;
	public $price;
	public $item_url;
	public $crowd_url;
    public $nickname;
    public $username;
    public $tel;
   
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'crowd_item';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {    	
        return [
            [['id','item_id','state','postage','useing','banner_flag'], 'integer'],
        	[['item_id'],'required'],
        	[['amRaised','tarAmount'],'number']	 ,
        	[['desc','memo','start_time','end_time','user_types','img_crowd_id'],'safe'],
        	[['item_id'], 'exist','targetClass' => '\backend\models\SysItem', 'targetAttribute'=>'id','message' => '单品不存在!'],
        ];
    }
    
 
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'item_id' => Yii::t('app','单品ID'),
            'banner_flag'=>Yii::t('app','轮播状态'),
            'user_types'=>Yii::t('app','用户类型'),
            'crowd_url'=>Yii::t('app','封面图'),
            'img_crowd_id'=>Yii::t('app','封面图'),
            'item_url'=>Yii::t('app','单品图片'),
            'state' => Yii::t('app','众筹状态'),
            'desc' => Yii::t('app','说明'),
            'memo' => Yii::t('app','配送地区描述'),
            'useing' => Yii::t('app','使用状态'),
            'start_time' => Yii::t('app','开始时间'),
            'end_time' => Yii::t('app','结束时间'),
        	'amRaised'=>Yii::t('app','已筹金额'),
        	'tarAmount'=>Yii::t('app','目标金额'),
        	'postage'=>Yii::t('app','是否包邮'),
        	'item' => Yii::t('app','单品名称'),
        ];
    }

    /**
     * 关联单品表
     */
    public function getItem(){
    	return $this->hasOne(SysItem::className(), ["id"=>"item_id"]);
    }
    
    /**
     * 获取众筹的图片
     */
    public function getImage(){
        return  $this->hasOne(SysImage::className(), ['id'=>'img_crowd_id']);
    }
   /**
    * 根据单品id获取他的材质列表
    * @param   $item_id
    */ 
    public function  getFabricByItem($item_id,$mid){
    	if(intval($mid)==0){
    		$sql="SELECT base_sys_preview.fid,base_sys_fabric.`name`,sys_image.`url`   FROM base_sys_preview
				LEFT JOIN  base_sys_fabric ON base_sys_preview.`fid`=base_sys_fabric.`id`
				LEFT JOIN sys_image ON base_sys_fabric.`img_small_id`=sys_image.`id`
				 WHERE item_id=:item_id   AND  base_sys_preview.`fid`!=0  GROUP BY fid";
    		$param=array(":item_id"=>$item_id);
    	}else{
    		$sql="SELECT base_sys_preview.fid,base_sys_fabric.`name`,sys_image.`url`   FROM base_sys_preview
				LEFT JOIN  base_sys_fabric ON base_sys_preview.`fid`=base_sys_fabric.`id`
				LEFT JOIN sys_image ON base_sys_fabric.`img_small_id`=sys_image.`id`
				 WHERE item_id=:item_id and    base_sys_preview.`fid`!=0 AND base_sys_preview.mid=:mid  GROUP BY fid";
    		$param=array(":item_id"=>$item_id,":mid"=>$mid);
    		
    	}
    	$f_list=ItemPreview::findBySql($sql,$param)->asArray()->all();
    	return $f_list;
    }
    /**
     * 根据单品id获取他的材质列表
     * @param unknown $iten_id
     */
    public function getMaterialByItem($item_id,$fid){
    	if(intval($fid)==0){
    		$sql="SELECT base_sys_preview.mid,base_sys_material.`name`,sys_image.`url`   FROM base_sys_preview
				LEFT JOIN  base_sys_material ON base_sys_preview.`mid`=base_sys_material.`id`
				LEFT JOIN sys_image ON base_sys_material.`img_small_id`=sys_image.`id`
				 WHERE item_id=:item_id  AND base_sys_preview.mid!=0  GROUP BY mid";
    		$param=array(":item_id"=>$item_id);
    	}else{
    		$sql="SELECT base_sys_preview.mid,base_sys_material.`name`,sys_image.`url`   FROM base_sys_preview
				LEFT JOIN  base_sys_material ON base_sys_preview.`mid`=base_sys_material.`id`
				LEFT JOIN sys_image ON base_sys_material.`img_small_id`=sys_image.`id`
				 WHERE item_id=:item_id and  base_sys_preview.mid!=0 AND   base_sys_preview.fid=:fid  GROUP BY mid";
    		$param=array(":item_id"=>$item_id,":fid"=>$fid);
    	}
    	$m_list=ItemPreview::findBySql($sql,$param)->asArray()->all();
    	return $m_list;
    }
    /**
     * 根据单品  面料 材质获取尺寸 
     */
    public function getSizeByItemFm($item_id,$fid,$mid){
    	if(intval($item_id)>0){
    		if(intval($mid)>0&&intval($fid)>0){
    			$sql="				 
					SELECT price_custom,sys_item_size.`size`,sys_item_size.id  FROM sys_item_prices
					LEFT JOIN sys_item_size ON sys_item_size.id=sys_item_prices.`size_id`
					WHERE sys_item_prices.item_id=:item_id  AND sys_item_prices.size_id!=0 and fabric_id=:fid AND material_id=:mid";
    			$param=array(":item_id"=>$item_id,":fid"=>$fid,":mid"=>$mid);
    		}else if($fid>0){
    			$sql="
					SELECT price_custom,sys_item_size.`size`,sys_item_size.id  FROM sys_item_prices
					LEFT JOIN sys_item_size ON sys_item_size.id=sys_item_prices.`size_id`
					WHERE sys_item_prices.item_id=:item_id AND sys_item_prices.size_id!=0 AND fabric_id=:fid ";
    			$param=array(":item_id"=>$item_id,":fid"=>$fid);
    		}else if($mid>0){
    			$sql="
					SELECT price_custom,sys_item_size.`size`,sys_item_size.id  FROM sys_item_prices
					LEFT JOIN sys_item_size ON sys_item_size.id=sys_item_prices.`size_id`
					WHERE sys_item_prices.item_id=:item_id  AND sys_item_prices.size_id!=0 AND material_id=:mid";
    			$param=array(":item_id"=>$item_id,":mid"=>$mid);
    		}else{
    		    //不存在
    			$sql="select id,size from sys_item_size where item_id=:item_id";
    			$param=array(":item_id"=>$item_id);
    		}
    		$sizeList=SysItemSize::findBySql($sql,$param)->asArray()->all();;
    		return $sizeList;
    	}
    	return array();
    }
   /**
    * 根据Item_id获取尺寸
    */ 
    public function getSizeByItem($item_id){
    	$sql="SELECT * FROM sys_item_size WHERE item_id=:item_id";
    	$param=array(":item_id"=>$item_id);
    	$sizeList=SysItemSize::findBySql($sql,$param)->asArray()->all();;
    	return $sizeList;
    }
    /**
     * 判断单品是否存在规格
     * @param unknown $item_id
     */
    public function getAllsizeByitem($item_id){
        $sql=" SELECT id  FROM sys_item_prices WHERE item_id =:item_id AND size_id!=0";
        $param=array(":item_id"=>$item_id);
        $prices=SysItemPrices::findBySql($sql,$param)->asArray()->all();
        if(count($prices)>0){
            return 1;
        }else{
            $sql="SELECT id FROM sys_item_size WHERE item_id=:item_id";
            $sizeList=SysItemSize::findBySql($sql,$param)->asArray()->all();
            if(count($sizeList)>0){
                return  1;
            }else{
                return 0;
            }
        }
        
    }
    
    /**
     * 根据itemid 判断单品是否存在组合
     */
    public function getPreviewByItem($item_id){
        $sql="select id from base_sys_preview where item_id=:item_id";
        $param=array(":item_id"=>$item_id);
        $preview=BaseSysPreview::findBySql($sql,$param)->asArray()->all();
        return count($preview);
    }
    /**
     * 根据规格获取价格
     */
    public function getPriceBySize($item_id,$fid,$mid,$sid){
    	//先获取单品价格，如果是从price表查询到规格，则累加两个价格
    	$sys_item=SysItem::findBySql("select price_base from sys_item where id=:id",array(":id"=>$item_id))->asArray()->all();
    	$base_price=doubleval($sys_item[0]['price_base']);
    	$sql="SELECT price_custom FROM sys_item_prices WHERE item_id=:item_id AND size_id=:size_id 
    			AND fabric_id=:fid AND material_id=:mid";
    	$param=array(":item_id"=>$item_id,":size_id"=>$sid,":fid"=>$fid,":mid"=>$mid);
    	$sys_item_price=SysItemPrices::findBySql($sql,$param)->asArray()->all();
    	if(count($sys_item_price)==0){
    		return $base_price;
    	}else{
    		$price_custom=doubleval($sys_item_price[0]['price_custom']);
    		$price=$price_custom+$base_price;
    		return $price; 
    	}
    }
    
    /**
     * 判断规格是否存在数据表
     */
    public function checkExit($item_id,$crowd_id,$fid,$mid,$sid){
        //查找组合
        $previewId=$this->checkExitPreview($item_id, $fid, $mid);
        if(intval($previewId>0)){
            $sql=" SELECT crowd_id  FROM crowd_price WHERE crowd_id=:cid AND  preview_id=:priview_id AND size=:sid";
            $param=array(":cid"=>$crowd_id,":priview_id"=>$previewId,":sid"=>$sid);
            $crowdPriceList=CrowdItemPrice::findBySql($sql,$param)->asArray()->all();
            return count($crowdPriceList);
        }else{
            return 0;//不存在组合
        }
    }
    /**
     * 根据面料 材质 判断是否存在
     * @param   $item_id
     * @param   $fid
     * @param   $mid
     * @return number
     */
    
    public function checkExitPreview($item_id,$fid,$mid){
        $sql="select id from base_sys_preview where item_id=:item_id and fid=:fid and mid=:mid";
        $param=array(":item_id"=>$item_id,":fid"=>$fid,":mid"=>$mid);
        $preview=ItemPreview::findBySql($sql,$param)->asArray()->all();
        if(count($preview)>0){
            $previewId=intval($preview[0]['id']);
            if($previewId>0){
                return $previewId;
            } 
        }
        return 0;
    }
    /**
     * 获取用户类型 id转name
     */
    public function getUsertypeStrById($user_types){
        $userAllArray=array("1"=>"注册用户","2"=>"设计师(申请中)","3"=>"认证VIP会员","4"=>"装饰公司","5"=>"城市运营商",
            "6"=>"协会","7"=>"服务商","8"=>"内部员工");
        $userArray=explode(",", $user_types);
        $user_Str='';
        $y=0;
        foreach($userArray as $type){
            for($i=2;$i<=count($userAllArray)+1;$i++){
                if($type==$i){
                    if($y==0){
                        $user_Str.=$userAllArray[$i];
                    }else{
                        $user_Str.=",".$userAllArray[$i];
                    }
                    $y++;
                }
            }
        }
        return $user_Str;
    }
    /**
     * 根据用户id数组转为str 
     */
    public function getUserStrByArray($user_types){
        $type_str='';
        if($user_types!=null){
            for($i=0;$i<count($user_types);$i++){
                if($i==0){
                    $type_str.=$user_types[$i];
                }else{
                    $type_str.=",".$user_types[$i];
                }
            }
        }else{
            $type_str='1,2,3,4,5,6,7,8';
        }
        return $type_str;
    }
    /**
     * 根据众筹id查询 众筹结束状态是否还有待退款订单
     * @param unknown $crow_id
     */
    public function checkExitRufund($crow_id){
        $sql="SELECT  pay_trade.id  FROM pay_trade
               WHERE  crowd_price_id IN  
            (SELECT   crowd_price.id crowd_price_id  FROM crowd_item
              LEFT JOIN crowd_price  ON crowd_price.`crowd_id`=crowd_item.`id`
                 WHERE  crowd_item.`id`=:crowd_id)
              and   price_state=1  and  trade_state =1   ";
        $param=array(":crowd_id"=>$crow_id);
        $payTrade=PayTrade::findBySql($sql,$param)->asArray()->all();
        if(count($payTrade)>0){
            return true;
        }else{
            return false;
        }
    }
}
